//
//  ViewController.swift
//  Edaixi-iOS
//
//  Created by 刘树华 on 2017/11/27.
//  Copyright © 2017年 刘树华. All rights reserved.
//

import UIKit
import Alamofire
import UITableView_FDTemplateLayoutCell
import MJRefresh
import SDWebImage
import SnapKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate {

 
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        print("\(self)DidLoad")
        view.backgroundColor = UIColor.white
        navigationItem.title = "第一个"
        self.automaticallyAdjustsScrollViewInsets = false
       
        
        
        
            //圆角需要继续   复制粘贴 操作
        let imageBG = UIImageView(imageName: "forkingdog")
        imageBG.center = view.center
        imageBG.bounds = CGRect(x: 0, y: 0, width: 128, height: 128)
        imageBG.backgroundColor = UIColor.red
        imageBG.layer.masksToBounds = true
    view.addSubview(imageBG)
        imageBG.makeCircular()
//        imageBG.makeRoundCorners(corner: .topLeft, radius: 60)
        
//        let maskV = UIView()
//        maskV.backgroundColor = UIColor.red
//        maskV.center = view.center
////        maskV.bounds = CGRect(x: 0, y: 0, width: 100, height: 100)
//        view.addSubview(maskV)
//        maskV.snp.makeConstraints { (make) in
//            make.center.equalToSuperview()
//            make.width.height.equalTo(100)
//        }
//
////        maskV.makeCircular()
//        maskV.makeRoundCorners(corner: .topLeft, radius: 10)
//       view.layoutIfNeeded()

        
//        let table = TouchTable(frame: CGRect(x: 0, y: 64, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-64), style: .plain)
//        table.tableFooterView = UIView()
//        table.delegate = self
//        table.estimatedRowHeight = 0
//        table.dataSource = self
//        table.register(TouchCell.classForCoder(), forCellReuseIdentifier: "cell")
//        self.view.addSubview(table)
        
//
//       let btn = UIButton(frame: CGRect(x: 100, y: 100, width: 40, height: 40))
//        btn.isEnabled = true
//        btn.addTarget(self, action: #selector(ViewController.btnClick(btn:)), for: .touchUpInside)
//        btn.backgroundColor = UIColor.red
//        self.view.addSubview(btn)
        
//       MultipartFormData().append(<#T##data: Data##Data#>, withName: <#T##String#>)
        
//       var  date = Date()
//       let zone = TimeZone.current
//       let time = zone.secondsFromGMT(for: date)
//       date = date.addingTimeInterval(TimeInterval(time))
//        MYDebugPrintf(msg: date)
        
//        print(TimeZone.current)
//        print(TimeZone.autoupdatingCurrent)
        
//        print("时间戳\(UNIX_TIME)")
        
//        MYDebugPrintf(msg: CurrentDate)
//        let testImageV = UIImageView()
//        testImageV.backgroundColor = UIColor.red
//        view.addSubview(testImageV)
//        testImageV.snp.makeConstraints { (make) in
//            make.center.equalToSuperview()
//        }
//

//
//        let greenV = UIView(frame: CGRect(x: 180, y: 100, width: 40, height: 50))
//        greenV.backgroundColor = UIColor.green
//      let tap =  UITapGestureRecognizer(target: self, action: #selector(ViewController.greenVTap))
//        tap.delaysTouchesBegan = false
//        greenV.addGestureRecognizer(tap)
//        self.view.addSubview(greenV)
        
        
        
        
        
    }
    
  
   
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TouchCell
       let last = self.view.convert(cell.input.frame, from: cell.input)
//        MYDebugPrintf(msg: last)
       let rect = cell.convert(cell.input.frame, to: self.view)
//        MYDebugPrintf(msg: rect)
        print("cellforRow->\(indexPath)")
        return cell
        
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        print("index->\(indexPath)")
        return 44
    }

    @objc func greenVTap ()  {

    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
         print("\(self)WillAppear")
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        print("\(self)DidAppear")
    }
    @objc func btnClick (btn:UIButton)  {
        MYDebugPrintf(msg: "\(btn.window)")
  
        
        navigationController?.pushViewController(FDTable(style: .plain), animated: true)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}

class TouchView: UIView {
    
    
    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
//        MYDebugPrintf(msg: "event")
        return super.point(inside: point, with: event)
    }
    
}

class webVC : BaseWebViewController {
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let ui = UIView()
        ui.backgroundColor = UIColor.red
        ui.center = view.center
        ui.bounds = CGRect(x: 0, y: 0, width: 150, height: 150)
        view.addSubview(ui)
        
    }
    
    override func loadRequest() -> URLRequest? {
        
      return  URLRequest(url: URL(string : "https://www.badu.com")!)
    }
    deinit {
        MYDebugPrintf(msg: "webVC析构")
    }
}

class SecVC : UIViewController,BusinessAlertDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()
        print("\(self)DidLoad")
         view.backgroundColor = UIColor.white
        navigationItem.title = "第二个"
        let btn = UIButton(frame: CGRect(x: 100, y: 100, width: 40, height: 40))
        btn.addTarget(self, action: #selector(btnClick(btn:)), for: .touchUpInside)
        btn.backgroundColor = UIColor.red
        self.view.addSubview(btn)
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print("\(self)WillAppear")
        print(self.tabBarController)
    }
    @objc func btnClick (btn:UIButton)  {

        
        BusinessAlert(delegate: self, title: nil, message: "测试时世世代代的哦啊都是电脑死哦哪都我安东is那都是女生开电脑卡死你的啦1", buttons: "确定").show()
        
        
//        navigationController?.pushViewController(ThirdVC(), animated: true)
    }
    func alertViewDidSelectWithIndex(_ alertView: BusinessAlert, index: NSInteger) {
        MYDebugPrintf(msg: index)
    }
    deinit {
        MYDebugPrintf(msg: "SECVC析构了")
    }
}

class ThirdVC: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        print("\(self)DidLoad")
         view.backgroundColor = UIColor.white
        navigationItem.title = "第三个"
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print("\(self)WillAppear")
    }
}

class TouchCell: UITableViewCell {
    var input : UITextField!
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
         input = UITextField(place: "试试")
        input.frame = CGRect(x: 100, y: 10, width: 100, height: 24)
        self.contentView.addSubview(input)
        
        
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

class TouchTable: UITableView {
    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
//        MYDebugPrintf(msg: "TouchTable时间")
        return super.point(inside: point, with: event)
    }
}

class FDTable: BaseTableViewController {
    var source = [FDEntity]()
    
    private var cacheHeight = [IndexPath:CGFloat]()
    override func viewDidLoad() {
        super.viewDidLoad()
        
      let filePath =  Bundle.main.path(forResource: "data", ofType: "json")
       
      let data = try! Data(contentsOf:  URL(fileURLWithPath: filePath!))
        let dic = try! JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as![String:Any]
       let dataArr = dic["feed"] as! [[String:String]]
        dataArr.forEach{
            source.append(FDEntity(dic: $0))
            
        }
//        tableView.estimatedRowHeight = 88
//        tableView.estimatedSectionFooterHeight = 0
//        tableView.estimatedSectionHeaderHeight = 0
//        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.register(FDCell.classForCoder(), forCellReuseIdentifier: "FDCell")
        
        tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            doSomeThingAfterDelay(inMain: true, time: 3, work: {
                self.tableView.reloadData()
               self.tableView.mj_header.endRefreshing()
            })
        })
        tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {
            doSomeThingAfterDelay(inMain: true, time: 3, work: {
                self.tableView.mj_footer.endRefreshing()
            })
        })
        tableView.mj_header.isAutomaticallyChangeAlpha = true
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationBarHidden = true
    }
    
//    override var prefersStatusBarHidden: Bool{
//        return true
//    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return source.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//        print("准备cell")
        let cell = tableView.dequeueReusableCell(withIdentifier: "FDCell", for: indexPath) as! FDCell
       configureCell(cell: cell, index: indexPath)
        
//        print("出列cell\(indexPath)")
        
//        print("计算出来的结果\(tableView.rectForRow(at: indexPath))")
        return cell
        
    }
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
//        print("计算高度\(indexPath)")
        return tableView.fd_heightForCell(withIdentifier: "FDCell", cacheBy: indexPath, configuration: { (cell) in
            
            self.configureCell(cell: cell as! FDCell, index: indexPath)
        })
//        if let height = cacheHeight[indexPath] {
//            print("取缓存\(indexPath)")
//            return height
//        }else{
//            print("自动计算\(indexPath)")
//            return UITableViewAutomaticDimension
//        }

//        return UITableViewAutomaticDimension

    }
//   override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
////        tableView.rectForRow(at: indexPath).height
//
//    cacheHeight[indexPath] = cell.contentView.height
////    print("index->\(indexPath) height===\( cell.contentView.height)")
//    }
    
    func configureCell(cell:FDCell,index:IndexPath)  {
        cell.fd_enforceFrameLayout = false
        if index.row % 2 == 0 {
            cell.accessoryType = .disclosureIndicator
        }else{
            cell.accessoryType = .checkmark
        }
        
        cell.setEntity(enti: source[index.row])
    }
    
}

class FDCell : UITableViewCell {
    let titleLabel = UILabel()
    
    let contentLable = UILabel()
    let imageV = UIImageView()
    let userName = UILabel()
    let time = UILabel()
    var sizeCon : Constraint?
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        
        titleLabel.textColor = UIColor.black
        titleLabel.numberOfLines = 0
        self.contentView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.left.equalTo(16)
            make.right.equalTo(-10)
            make.top.equalTo(10)
        }
        contentLable.textColor = UIColor.black
        contentLable.numberOfLines = 0
        self.contentView.addSubview(contentLable)
        contentLable.snp.makeConstraints { (make) in
            make.left.equalTo(titleLabel.snp.left)
            make.right.equalTo(-10)
          make.top.equalTo(titleLabel.snp.bottom).offset(6)
        }
        
        contentView.addSubview(imageV)
        imageV.snp.makeConstraints { (make) in
            make.left.equalTo(titleLabel.snp.left)
//            make.right.greaterThanOrEqualTo(-16)
           
            sizeCon =  make.size.equalTo(CGSize(width: 0, height: 0)).constraint;
//           make.size.equalTo(CGSize(width: 128, height: 128))
            
            make.top.equalTo(contentLable.snp.bottom).offset(8)
        }
        userName.textColor = UIColor.darkGray
        userName.numberOfLines = 0
        contentView.addSubview(userName)
        userName.snp.makeConstraints { (make) in
            make.left.equalTo(contentLable.snp.left)
            make.top.equalTo(imageV.snp.bottom).offset(8)
            make.bottom.equalTo(-4)
        }
//        time.textColor = UIColor.blue
//        time.numberOfLines = 0
//        contentView.addSubview(time)
//        time.snp.makeConstraints { (make) in
//            make.right.equalTo(-10)
//            make.lastBaseline.equalTo(userName.snp.lastBaseline)
//        }
        
        
        
    }
    func setEntity (enti:FDEntity)  {
        titleLabel.text = enti.title
        contentLable.text = enti.content
        
       sizeCon?.update(offset: 128)
//        userName.snp.updateConstraints { (make) in
//            make.left.equalTo(contentLable.snp.left)
//            make.top.equalTo(imageV.snp.bottom).offset(8)
//            make.bottom.equalTo(-4)
//        }
//       imageV.sd_setImage(with: URL(string: validStr(data: enti.imageName)), completed: nil)
//        imageV.snp.makeConstraints { (make) in
//            make.width.height.equalTo(128)
//        }
        imageV.sd_setImage(with: URL(string: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1512707417776&di=a67d14d7a0949a967d4a0270418ab6a0&imgtype=0&src=http%3A%2F%2Fm.qqzhi.com%2Fupload%2Fimg_5_2258173813D2979628568_23.jpg"), placeholderImage: nil, options: SDWebImageOptions.retryFailed, progress: nil, completed: nil)
        
//        UIView().contentScaleFactor
//        CALayer().contentsScale
//        imageV.image = UIImage(named:validStr(data: enti.imageName))
        userName.text = enti.userName
        time.text = enti.time
    }
   
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

struct FDEntity  {
    var title:String?
    var content:String?
    var userName:String?
    var time:String?
    var imageName:String?
    init(dic:[String:String]) {
        title = dic["title"]
        content = dic["content"]
        userName = dic["username"]
        time = dic["time"]
        imageName = dic["imageName"]
    }
  
    
}


class TECollection : BaseCollectionViewController,UICollectionViewDelegateFlowLayout {
    override func viewDidLoad() {
        super.viewDidLoad()
    
        collectionView?.register(TEItem.classForCoder(), forCellWithReuseIdentifier: "TEItem")
        collectionView?.backgroundColor = UIColor.white
    }
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 50
    }
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let item = collectionView.dequeueReusableCell(withReuseIdentifier: "TEItem", for: indexPath) as! TEItem
        if indexPath.row % 3 == 0 {
            item.txtLable.text = ",是是不是是滴是滴思考到三年迪士尼大款了 撒大声地建设路口 世界第三将打击到是的纳税的女生开电脑啦是的哪到哪看阿兰卡是电脑能带你打"
        }else if indexPath.row % 3 == 1 {
            item.txtLable.text = ",滴是滴思考到三年迪士尼大款了 撒大声地建设路口 "
        }else{
             item.txtLable.text = ",是是不是是滴是滴思考到三年迪士尼大款了 撒大声地建设路口 是是不是是滴是滴思考到三年迪士尼大款了 撒大声地建设路口 世界第三将打击到是的纳税的女生开电脑啦是的哪到哪看阿兰卡是电脑能带你打"
        }
       
        return item
        
    }
//    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
//      let attri = collectionViewLayout.layoutAttributesForItem(at: indexPath)
//        return CGSize(width: 150, height: 100)
//    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 10
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 10
    }
    
}
class TEItem : UICollectionViewCell {
    var txtLable:UILabel!
    
    private var isHeightCalculated: Bool = false
    override init(frame: CGRect) {
        super.init(frame: frame)
        txtLable = UILabel( textColor: UIColor.black, bgColor: UIColor.cyan)
        txtLable.numberOfLines = 0
        txtLable.lineBreakMode = .byTruncatingTail
        contentView.addSubview(txtLable)
        txtLable.backgroundColor = UIColor.red
        txtLable.snp.makeConstraints { (make) in
            
            make.edges.equalTo(UIEdgeInsetsMake(5, 5, -5, -5))
        }
    }
//    override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
////        MARK 宽度自适应
////        var layoutSize = layoutAttributes.size
////        layoutSize.width = UIViewNoIntrinsicMetric
////      var contentFitSize =  contentView.systemLayoutSizeFitting(layoutSize, withHorizontalFittingPriority: UILayoutPriority.fittingSizeLevel, verticalFittingPriority: UILayoutPriority.required)
////
////        if contentFitSize == layoutAttributes.size {
////            return layoutAttributes
////        }else{
////            let att  = layoutAttributes.copy() as! UICollectionViewLayoutAttributes
////            contentFitSize.height = layoutSize.height
////            att.frame = CGRect(origin: layoutAttributes.frame.origin, size: contentFitSize)
////            return att
////        }
//        
////       Mark 高度自适应
////            var sizeFit = layoutAttributes.size
////            sizeFit.height = UIViewNoIntrinsicMetric
////            var fitSize = contentView.systemLayoutSizeFitting(sizeFit, withHorizontalFittingPriority: UILayoutPriority.required, verticalFittingPriority: UILayoutPriority.fittingSizeLevel)
////            if fitSize == layoutAttributes.size {
////                isHeightCalculated = true
////                return layoutAttributes
////            }else{
////                let fitAttri = layoutAttributes.copy() as! UICollectionViewLayoutAttributes
////                fitSize.width = sizeFit.width
////                if fitSize.height == CGFloat.greatestFiniteMagnitude{
////                    fitSize.height = layoutAttributes.size.height
////                }
////                fitAttri.frame = CGRect(origin: layoutAttributes.frame.origin, size: fitSize)
////                isHeightCalculated = true
////                return fitAttri
////            }
//        
//      
//
//    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}
